﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace MyFirstSolution.Common
{
    /// <summary>
    /// INI配置文件读写类
    /// </summary>
    public class IniFile
    {
        public string path;     //INI文件名

        //声明读写INI文件的API函数
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        //类的构造函数，传递INI文件名
        public IniFile(string INIPath)
        {
            path = INIPath;
        }

        /// <summary>
        /// 写INI文件
        /// </summary>
        /// <param name="Section">节名称</param>
        /// <param name="Key">键名称</param>
        /// <param name="Value">值--字符串类型</param>
        public void IniWriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this.path);
        }

        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="Section">节名称</param>
        /// <param name="Key">键名称</param>
        /// <returns>读出的值--字符串类型（最长不超过512Bytes）</returns>
        public string IniReadValue(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(1024);
            int i = GetPrivateProfileString(Section, Key, "", temp, 1024, this.path);
            return temp.ToString().Trim();
        }

    }
}
